<?php

function transformDate($date, $delimeter) {
    $d = explodeDate($date, $delimeter);
    if (!isset($d[1])) {
        return $date;
    }
    if ($d[0][0] == '0') {
        $D = substr($d[0], 1);
    } else {
        $D = $d[0];
    }
    if ($d[1][0] == '0') {
        $M = substr($d[1], 1);
    } else {
        $M = $d[1];
    }
    return $D . '.' . $M . '.' . $d[2];
}

function explodeDate($date, $delimeter) {
    return explode($delimeter, $date);
}

function dateToU($date) {
    $d = explodeDate($date, '-');
    return date("U", mktime(12, 0, 0, $d[1], $d[2], $d[0]));
}

function jeSviatok($date) {
    $d = date('j', $date);
    $m = date('n', $date);
    $y = date('Y', $date);
    $sv_s = "SELECT id FROM sviatok WHERE den = '" . $d . "' AND mesiac='" . $m . "' AND rok='" . $y . "' ";
    $sv_q = MySQL_Query($sv_s);
    $sv = MySQL_Fetch_Array($sv_q);
    if (isset($sv['id'])) {
        return true;
    } else {
        return false;
    }
}

function sviatokAleboVikend($date) { // 
    $w = date("w", $date);

    if (($w == 6) || ($w == 0) || (jeSviatok($date))) {
        return true;
    }

    return false;
}

function obklucenyVikend($date) {
    $plus = 86400;
    $pocet = 0;
    while ((date("w", $date + $plus) == 0) || (date("w", $date + $plus) == 6) || (jeSviatok($date + $plus))) {
        $plus += 86400;
        $pocet += 86400;
    }
    return $pocet;
}

include "../inc/db_connect.php";

if ((isset($_POST['company']) && isset($_POST['date'])) || (isset($_GET['company']) && isset($_GET['date']))) {
    if (isset($_GET['company']))
        $_POST['company'] = $_GET['company'];
    if (isset($_GET['date']))
        $_POST['date'] = $_GET['date'];
    $spol_s = "SELECT * FROM spolocnost WHERE id = '" . $_POST['company'] . "'";
    $spol_q = MySQL_Query($spol_s);
    $spol_n = MySQL_Num_Rows($spol_q);
    $spol = MySQL_Fetch_Array($spol_q);
    
    $D = explode(':', $_POST['date']);
    $M = $D[0];
    $Y = $D[1];
    $name = $M . '_' . $Y . '_';
    $name .= str_replace(' ', '-', $spol['nazov']);

    if ($M < 10) {
        $M = '0' . $M;
    }

    $myFile = '../xmls/' . $name . '.xml';
    $fh = fopen($myFile, 'w') or die("can't open file");

    $text = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
    $text .= "\r\n";
    $text .= '<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
    $text .= "\r\n";

    $PD = date("t", mktime(1, 1, 1, $M, 2, $Y));
    $date_OD = date("U",  mktime(0, 0, 0, $M, 1, $Y));
    $date_DO = date("U",  mktime(23, 59, 59, $M, $PD, $Y)); 
    $doch_s = "SELECT dochadzkazamfalk.date,dochadzkazamfalk.zid,praca.SPIN,dochadzkazamfalk.type,z.osobneCislo,z.fond FROM dochadzkazamfalk,z,praca WHERE z.spolid = '" . $spol['id'] . "' AND dochadzkazamfalk.zid = z.id AND dochadzkazamfalk.type=praca.skratka AND praca.nepr='1' AND (dochadzkazamfalk.date BETWEEN '" . $date_OD . "' AND '" . $date_DO . "') ORDER BY dochadzkazamfalk.zid ASC, dochadzkazamfalk.date ASC";
    $doch_q = MySQL_Query($doch_s);
    $doch_n = MySQL_Num_Rows($doch_q);
    $pole_zaznamov = array();
    $pole_vysledkov = array();
    while ($doch = MySQL_Fetch_Array($doch_q)) {
        $pole_zaznamov[count($pole_zaznamov)] = $doch;
    }

    for ($i = 0; $i < count($pole_zaznamov); $i++) {

        $vysledok = array();
        $vysledok["Zid"] = $user = $pole_zaznamov[$i]['zid'];
        $vysledok["OsobneCisl"] = $pole_zaznamov[$i]['osobneCislo'];
        $vysledok["KOD"] = $code = $pole_zaznamov[$i]['SPIN'];
        $skratka = $pole_zaznamov[$i]['type'];
        $datum = date("Y-m-d",$pole_zaznamov[$i]['date']);
        $d = explodeDate($datum, '-');
        $dateToU = dateToU($datum);
        $vysledok["DATUM_OD"] = $d[2] . '.' . $d[1] . '.' . $d[0];
        $vysledok["DATUM_DO"] = $d[2] . '.' . $d[1] . '.' . $d[0];

        $obklucenyVikend = obklucenyVikend($dateToU);
        $vysledok["PRAC_DNI"] = 1;
        if ($pole_zaznamov[$i]['pid'] == 8)
            $vysledok["HODINY"] = 4;
        else
            $vysledok["HODINY"] = ($pole_zaznamov[$i]['fond'] / 5);
        
        $datumPorovnanie = $dateToU;
        $posun = 0;

        //echo $i . 'i<br/>';
        //echo $user . '<br/>';
        //echo $code . '<br/><p style="padding: 30px;">';
        if (($i + 1) < count($pole_zaznamov)) {
            $skoc = -1;
            for ($j = $i + 1; $j < count($pole_zaznamov); $j++) {
                $datumm = date("Y-m-d",$pole_zaznamov[$j]['date']);
                $dateToUnext = dateToU($datumm);
                $moze = false;
                //echo $j . 'j<br/>';
                //echo $pole_zaznamov[$j]['zid'] . '<br/>';
                //echo $pole_zaznamov[$j]['SPIN'] . '<br/>';
                if (($user == $pole_zaznamov[$j]['zid']) && ($code == $pole_zaznamov[$j]['SPIN'])) {
                    //echo 'voslo<br/>';
                    if (($dateToUnext - $dateToU - $posun) == (($j - $i) * 86400)) {
                        $moze = true;
                    } else {
                        $temp = 0;
                        for ($k = 1; $k < (($dateToUnext - $datumPorovnanie) / 86400); $k++) {
                            if (!sviatokAleboVikend($datumPorovnanie + $k * 86400)) {
                                $temp++;
                            } else {
                                $posun += 86400;
                            }
                        }
                        if ($temp == 0) {
                            $moze = true;
                        }
                    }
                } else {
                    $j = count($pole_zaznamov) + 1;
                }
                if ($moze) {
                    $datumm = date("Y-m-d",$pole_zaznamov[$j]['date']);
                    $dd = explodeDate($datumm, '-');
                    $vysledok["DATUM_DO"] = $dd[2] . '.' . $dd[1] . '.' . $dd[0];
                    $vysledok["PRAC_DNI"]++;
                    if ($pole_zaznamov[$j]['pid'] == 8)
                        $vysledok["HODINY"] += 4;
                    else
                        $vysledok["HODINY"] += ($pole_zaznamov[$i]['fond'] / 5);
                    $skoc = $j;
                    $datumPorovnanie = $dateToUnext;
                }
            }
            if ($skoc != -1)
                $i = $skoc;
        }
        //echo '</p>';
        if ($pid == 4 || $pid == 10) {
            $vysledok["PRAC_DNI"] = 0;
            $vysledok["HODINY"] = 0;
        }


        $pole_vysledkov[count($pole_vysledkov)] = $vysledok;
    }

    //var_dump($pole_vysledkov);

    foreach ($pole_vysledkov as $v) {
        $text .= '<Row>';
        $text .= "\r\n";
        $text .= '<PP_ID>0</PP_ID>';
        $text .= "\r\n";
        $text .= '<OSOBNECISL>' . $v['OsobneCisl'] . '</OSOBNECISL>';
        $text .= "\r\n";
        $text .= '<DATUMPLAT>' . transformDate(('1.' . $M . '.' . $Y), '.') . '</DATUMPLAT>';
        $text .= "\r\n";
        $text .= '<KOD_MZ>' . $v['KOD'] . '</KOD_MZ>';
        $text .= "\r\n";
        $text .= '<PRAC_DNI>' . $v['PRAC_DNI'] . '</PRAC_DNI>';
        $text .= "\r\n";
        $text .= '<HODINY>' . $v['HODINY'] . '</HODINY>';
        $text .= "\r\n";
        $text .= '<SUMA>0</SUMA>';
        $text .= "\r\n";
        $text .= '<DATUM_OD>' . transformDate($v['DATUM_OD'], '.') . '</DATUM_OD>';
        $text .= "\r\n";
        $text .= '<DATUM_DO>' . transformDate($v['DATUM_DO'], '.') . '</DATUM_DO>';
        $text .= "\r\n";
        $text .= '<MANDANT_ID>44428901</MANDANT_ID>';
        $text .= "\r\n";
        $text .= '</Row>';
        $text .= "\r\n";
    }

    $text .= '</Root>';

    $xml_s = "SELECT id FROM xmls WHERE cid='" . $_POST['company'] . "' AND month='" . $M . "' AND year='" . $Y . "'";
    $xml_q = MySQL_Query($xml_s);
    $xml_n = MySQL_Num_Rows($xml_q);


    $date = date("Y-m-d H:i:s");
    if ($xml_n != 0) {
        $xml = MySQL_Fetch_Array($xml_q);
        $xs = "UPDATE xmls SET date = '" . $date . "', text = '" . $text . "' WHERE id = '" . $xml['id'] . "' ";
        $xq = MySQL_Query($xs);
    } else {
        $xs = "INSERT INTO xmls (id, cid, month, year, file, date, text) VALUES (NULL, '" . $_POST['company'] . "', '" . $M . "', '" . $Y . "', '" . $name . "', '" . $date . "', '" . $text . "')";
        $xq = MySQL_Query($xs);
    }


    fwrite($fh, $text);

    fclose($fh);

    echo 1;
    echo '#Export neprítomnosti: <a href="get_fileXml.php?cid=' . $_POST['company'] . '&amp;m=' . $M . '&amp;y=' . $Y . '">' . $name . '.xml (' . $date . ')</a>';
}
?>
